package com.topnav.mc.uitls;

import com.js.lib.cache.SysCache;
import com.js.lib.exception.CustomException;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.common.Constant;
import com.topnav.mc.exception.ExceptionMsg;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PermissionGradeUtil {
    @Autowired
    private SysCache sysCache;

    /**
     * 取得 PermissionGrade
     * @return
     */
    public PermissionGrade getPmGrade(){
        PermissionGrade PermissionGrade = null;
        String token = MDC.get(Constant.MDC_TOEKN);
        if (!(token==null || "".equals(token))){
            Object obj=null;
            if ((obj= sysCache.hget(Constant.USER_ORGANIZATION_ROLE,token))!=null){
                return  (PermissionGrade)obj;
            }
        }
        return null;
    }

    /**
     * 由token取PermissionGrade
     * @param token
     * @return
     */
    public PermissionGrade getPmGrade(String token){
        PermissionGrade PermissionGrade = null;
        if (!(token==null || "".equals(token))){
            Object obj=null;
            if ((obj= sysCache.hget(Constant.USER_ORGANIZATION_ROLE,token))!=null){
                return  (PermissionGrade)obj;
            }
        }
        return null;
    }

    /**
     * 保存权限到缓存
     * @param token
     * @param permissionGrade
     * @param tokenValidity
     */
    public void setPmGrade(String token,PermissionGrade permissionGrade,long tokenValidity){
        sysCache.hset(Constant.USER_ORGANIZATION_ROLE,token,permissionGrade,tokenValidity);
    }



    /**
     * 取得 PermissionGrade 如果取不到则报异常
     * @return
     */
    public PermissionGrade getPmGradeCheck(){
        PermissionGrade PermissionGrade = getPmGrade();
        if (PermissionGrade == null){
            throw new CustomException(
                    ExceptionMsg.ERROR_AUTHENTICATION_EFFE.getCode(),
                    ExceptionMsg.ERROR_AUTHENTICATION_EFFE.getDesc());
        }
        return PermissionGrade;

    }

    /**
     * 移除
     * @param token
     */
    public void removePmGrade(String token){
        sysCache.hdel(Constant.USER_ORGANIZATION_ROLE, token);
    }

}
